package com.cssl.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cssl.mapper.BasicNumbersMapper;
import com.cssl.pojo.BasicNumbers;
import com.cssl.service.BasicNumbersService;
import com.ruoyi.common.core.utils.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class BasicNumbersServiceImpl extends ServiceImpl<BasicNumbersMapper, BasicNumbers> implements BasicNumbersService {
   @Resource
    private BasicNumbersMapper basicNumbersMapper;
    @Override
    public BasicNumbers selectBasicNumbersByEnCode(Long enCode)
    {
        return basicNumbersMapper.selectBasicNumbersByEnCode(enCode);
    }

    /**
     * 查询自动生成编号列表
     *
     * @param basicNumbers 自动生成编号
     * @return 自动生成编号
     */
    @Override
    public List<BasicNumbers> selectBasicNumbersList(BasicNumbers basicNumbers)
    {
        return basicNumbersMapper.selectBasicNumbersList(basicNumbers);
    }

    /**
     * 新增自动生成编号
     *
     * @param basicNumbers 自动生成编号
     * @return 结果
     */
    @Override
    public int insertBasicNumbers(BasicNumbers basicNumbers)
    {
        basicNumbers.setCreateTime(DateUtils.getNowDate());
        basicNumbers.setLastDate(DateUtils.getNowDate());
        basicNumbers.setEnNum(0L);
        basicNumbers.setEnRules(generateNumbers(basicNumbers));
        //System.out.println(basicNumbers);
        basicNumbers.setIsDel(0L);
        return basicNumbersMapper.insertBasicNumbers(basicNumbers);
    }

    /**
     * 修改自动生成编号
     *
     * @param basicNumbers 自动生成编号
     * @return 结果
     */
    @Override
    public int updateBasicNumbers(BasicNumbers basicNumbers)
    {
        basicNumbers.setEnRules(generateNumbers(basicNumbers));
        basicNumbers.setUpdateTime(new Date());
        return basicNumbersMapper.updateBasicNumbers(basicNumbers);
    }

    /**
     * 批量删除自动生成编号
     *
     * @param enCodes 需要删除的自动生成编号主键
     * @return 结果
     */
    @Override
    public int deleteBasicNumbersByEnCodes(Long[] enCodes)
    {
        return basicNumbersMapper.deleteBasicNumbersByEnCodes(enCodes);
    }

    /**
     * 删除自动生成编号信息
     *
     * @param enCode 自动生成编号主键
     * @return 结果
     */
    @Override
    public int deleteBasicNumbersByEnCode(Long enCode)
    {
        return basicNumbersMapper.deleteBasicNumbersByEnCode(enCode);
    }

    /**
     * 根据规则自动生成编号
     * @param enCode 主键
     * @return 编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized String automaticallyNumbers(Long enCode) {
        return automaticallyNumbers(enCode, false);
    }

    /**
     * 根据规则自动生成编号
     * @param enCode 主键
     * @param preview 是否为预览模式，true=仅预览不消费流水号，false=正常消费流水号
     * @return 编号
     */
    @Transactional(rollbackFor = Exception.class)
    public synchronized String automaticallyNumbers(Long enCode, boolean preview) {
        //编码
        String serialNumber=null;

        BasicNumbers basicNumbers = selectBasicNumbersByEnCode(enCode);

        // 判断是否需要重置序号（预览模式和消费模式都需要检查）
        Long currentEnNum = basicNumbers.getEnNum();
        boolean needReset = false;

        // 检查是否需要根据时间规则重置序号
        Instant instant = basicNumbers.getLastDate().toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate oldDate = instant.atZone(zoneId).toLocalDate();
        LocalDate newDate = LocalDate.now();
        Period period = Period.between(oldDate, newDate);

        if (basicNumbers.getEnFlushed() == 1) {
            // 按天刷新：如果日期不同，就重置序号
            needReset = !oldDate.equals(newDate);
        } else if (basicNumbers.getEnFlushed() == 2) {
            // 按月刷新
            needReset = period.getMonths() > 0;
        } else if (basicNumbers.getEnFlushed() == 3) {
            // 按年刷新
            needReset = period.getYears() > 0;
        }

        // 如果需要重置，使用0作为基础值
        if (needReset) {
            currentEnNum = 0L;
        }

        SimpleDateFormat simpleFormatter=new SimpleDateFormat(basicNumbers.getEnTime());
        //当前时间格式
        String timeFormat = simpleFormatter.format(new Date());

        //流水号：使用当前序号（可能已重置为0）加上步长
        Long enNum = currentEnNum + basicNumbers.getEnStep();

        if (enNum>basicNumbers.getMaxNum()){
            return null;
        }

        if (!preview) {
            // 仅在非预览模式下更新数据库
            BasicNumbers numbers = new BasicNumbers();
            numbers.setEnCode(basicNumbers.getEnCode());
            numbers.setEnNum(enNum);
            numbers.setLastDate(new Date());
            basicNumbersMapper.updateBasicNumbers(numbers);
        }

        serialNumber = basicNumbers.getEnPrefix()+timeFormat+String.format("%0"+basicNumbers.getMaxNum().toString().length()+"d",enNum);
        return serialNumber;
    }



    /**
     * 生成编号案例
     * @param basicNumbers 类
     * @return 返回编号
     */
    private String generateNumbers(BasicNumbers basicNumbers){
        //编码
        String serialNumber=null;
        SimpleDateFormat simpleFormatter=new SimpleDateFormat(basicNumbers.getEnTime());
        //当前时间格式
        String timeFormat = simpleFormatter.format(new Date());
        serialNumber= basicNumbers.getEnPrefix()+timeFormat+String.format("%0"+basicNumbers.getMaxNum().toString().length()+"d",1);
        return serialNumber;
    }
}
